import pageination from '../../components/pageination/pageination.vue'
export default {
	data() {
		return {
			//数据
      type: 0,
      AgreementObj: {},

      attId: 0,

      validate2: {},
      SpecialistUpd: false, // 修改
      SpecialistView: false, // 建设查看model
      obj: {}, // 建设
      id: 0,
      cid: 0,
      startTime: '',
      endTime: '',
      page2: 1,
      size2: 10,
      total2: 0,
      validate: {}, //验证对象
      temApplicationStatus: false, // 基地终止
      construction: [], // 基地建设列表
      FileUploadAtt: [], // 建设附件
      attachment: '', // 建设url
      quitFile: '', // 退出申请的附件
      baseName: '',
      baseId: '',
      baseData: [], // 基地数据
      thatUrl: this.urls.baseUrl,
      base: {}, // 基地详情
      Application: false, // base详情
      baseSelect: [], // 基地下拉框
			total: 0, //总条数
			page: 1, //当前页
			size: 10, //每页显示条数
			demandModelShow: false,
			Specialist: false,
			Tickets: false,
			QuitApplication: false,
			ApplicationStatus: false,
			uploadNum: 0,
			FileUpload: [],
      userId: this.get("userInfo").id
		}
	},
	components: {
		pageination
	},
	created() { //调用方法
		let that = this;
		that.getBaseSelect();
		console.log(that.userId)

	},
	mounted() {
    //加载表单验证
    this.validate2 = $("#BaseConstructionThe2").validate({
      ignore: [],
      rules: {
        baseId: { // 名称
          required: true,
        },
        startTime: { // 身份证
          required: true,
        },
        endTime: { // 邮箱
          required: true,
        },
        constructionMatters: { // 性别
          required: true,
          maxlength: 10000
        }
      },
      messages: {
        baseId: { // 名称
          required: '请选择基地',
        },
        startTime: { // 身份证
          required: '开始时间不能为空',
        },
        endTime: { // 邮箱
          required: '结束时间不能为空',
        },
        constructionMatters: { // 性别
          required: '建设事项不能为空',
          maxlength:'建设事项最多只能输入10000字！'
        }
      },
      /*errorElement: "em",
      errorPlacement: function(error, element) {
        error.appendTo(element.parents(".error-box").children(".error-msg"));
      }*/
    });

    //加载表单验证 建设
    this.validate = $("#BaseConstructionThe").validate({
      ignore: [],
      rules: {
        baseId: { // 名称
          required: true,
        },
        startTime: { // 身份证
          required: true,
        },
        endTime: { // 邮箱
          required: true,
        },
        constructionMatters: { // 性别
          required: true,
          maxlength: 10000
        }
      },
      messages: {
        baseId: { // 名称
          required: '请选择基地',
        },
        startTime: { // 身份证
          required: '开始时间不能为空',
        },
        endTime: { // 邮箱
          required: '结束时间不能为空',
        },
        constructionMatters: { // 性别
          required: '建设事项不能为空',
          maxlength:'建设事项最多只能输入10000字！'
        }
      },
      /*errorElement: "em",
      errorPlacement: function(error, element) {
        error.appendTo(element.parents(".error-box").children(".error-msg"));
      }*/
    });

  },

	methods: { //写函数方法
    // 基地下拉框
    getBaseSelect: function ( ) {
      let that = this;
      if(! that.userId){return;};

       setTimeout(function () {
         // 基地展示数据
         that.$post(
           that.urls.basePage,
           { "pageNum": 1, "list": [1, 2,5,6,3],
             "pageSize": 9999999 , "userId": that.userId}
         )
           .then(function(res) {
             if(res.success) {
               let select = [];
               if (res.pageInfo.list.length > 0) {
                 res.pageInfo.list.forEach(function (e) {
                   if (e.status == 1 || e.status == 5 || e.status === 2) {
                     select.push({"id": e.id, "name": e.name});
                   }
                 })
                 that.baseSelect = select;
               }

             }
           })
       }, 700);

    },

    // 基地数据
    getBase: function ( ) {
      let that = this;
      if(! that.userId){return;};
      let name = $('#searchRoleVal').val();
      // 基地展示数据
      that.$post(
        that.urls.basePage,
        { "pageNum": that.page, "list": [1, 2,5,6,3],
          "pageSize": that.size , "name": name ,"userId": that.userId}
      )
        .then(function(res) {
          if(res.success) {
            that.baseData = res.pageInfo.list;
            that.total = res.pageInfo.total;
            that.page = res.pageInfo.pageNum;


          }
        })
    },
    //查看
    toView:function(id){
      this.Application = true;
      this.base.picture="";
      let that = this;
      console.log('基地详情id' + id)
      // 基地信息
      that.$post(
        that.urls.getBaseAreas, {
          "id": id,
        }
      )
        .then(function(res) {
          if(res.success) {
            that.base = res.data;
            let type = that.base.type;
            if(type == 0) {
              that.base.type = '现代农业综合示范基地';
            } else if(type == 1) {
              that.base.type = '现代农业特色产业基地';
            } else if(type == 2) {
              that.base.type = '乡村建设研究实践基地';
            } else if(type == 3) {
              that.base.type = '新农村建设分布式服务站';
            }
          }
        })

    },
    // 基地搜索
    searchBase: function () {
      this.getBase();
    },
		//页码切换执行方法
		pageFn: function(val, pid) {
			this.page = parseInt(val);
      this.getBase();
			//此处调列表数据接口
		},
		/**返回子组件用户选择的一页显示条数**/
		obtainChild: function(data) {
			this.row = data;
		},
    //页码切换执行方法 基地建设
    pageFn2: function(val, pid) {
      this.page2 = parseInt(val);
      this.AllTickets();
      //此处调列表数据接口
    },
    /**返回子组件用户选择的一页显示条数 基地建设**/
    obtainChild2: function(data) {
      this.row = data;
    },

    touchOffIdInput(n) {
			this.uploadNum = n;
			if(n == 1) {
				$("#handIdFront").click();
			}
		},
    /**文件上传(多文件)js 申请退出**/
    idFrontImg: function(event) {
      let that = this;
      let files = event.currentTarget.files;
      if (!that.fileGlobalFilter(files)) {
        return;
      }
      let formData = new FormData();
      for(let i = 0, len = files.length; i < len; i++) {
        formData.append('fileNames', files[i]);
      }
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
        }
      };
      that.$post(
        that.urls.upload,
        formData,
        config
      )
        .then(function(res) {
          if(res.success) {
            let fileInfos = res.data;
            let urls = [];
            let names = [];
            for(let i = 0, len = fileInfos.length; i < len; i++) {
              urls.push(fileInfos[i].url);
              names.push(that.getFileName(fileInfos[i].url));
            }
            that.FileUpload = names;
            that.quitFile = urls.join(";");
          }
        })
      console.log(that.FileUpload )
    },

    // 建设附件点击
    touchOffIdInput2(n) {
      this.uploadNum = n;
      if(n == 1) {
        $("#handIdFront2").click();
      }
    },
    /**文件上传(多文件)js  建设新增**/
    idFrontImg2: function(event) {
      let that = this;
      let files = event.currentTarget.files;
      if (!that.fileGlobalFilter(files)) {
        return;
      }
      let formData = new FormData();
      for(let i = 0, len = files.length; i < len; i++) {
        formData.append('fileNames', files[i]);
      }
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
        }
      };
      that.$post(
        that.urls.upload,
        formData,
        config
      )
        .then(function(res) {
          if(res.success) {
            let fileInfos = res.data;
            let urls = [];
            let names = [];
            for(let i = 0, len = fileInfos.length; i < len; i++) {
              urls.push(fileInfos[i].url);
              names.push(that.getFileName(fileInfos[i].url));
            }
            that.FileUploadAtt = names;
            that.attachment = urls.join(";");
            that.validate.resetForm();
          }
        })
    },

    changeInput: function () {
      this.validate.resetForm();
    },
	changeTime:function(){
		if(this.obj.startTime){
			$("#startTime-error").css("display","none");
		}else{
			$("#startTime-error").css("display","block");
		}
		if(this.obj.endTime){
			$("#endTime-error").css("display","none");
		}else{
			$("#endTime-error").css("display","block");
		}
	},
    // 建设附件点击
    touchOffIdInput3(n) {
      this.uploadNum = n;
      if(n == 1) {
        $("#handIdFront3").click();
      }
    },
    /**文件上传(多文件)js  建设修改**/
    idFrontImg3: function(event) {
      let that = this;
      let files = event.currentTarget.files;
      if (!that.fileGlobalFilter(files)) {
        return;
      }
      let formData = new FormData();
      for(let i = 0, len = files.length; i < len; i++) {
        formData.append('fileNames', files[i]);
      }
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
        }
      };
      that.$post(
        that.urls.upload,
        formData,
        config
      )
        .then(function(res) {
          if(res.success) {
            let fileInfos = res.data;
            let urls = [];
            let names = [];
            for(let i = 0, len = fileInfos.length; i < len; i++) {
              urls.push(fileInfos[i].url);
              names.push(that.getFileName(fileInfos[i].url));
            }
            that.FileUploadAtt = names;
            that.attachment = urls.join(";");
            that.obj.attachment = urls.join(";");
          }
        })
    },

    // 提交建设
    subBaseConstruction: function () {
      let that = this;

      let flg = that.validate.form();
        if(! flg){
          return;
        }

     let  dataObj = that.combinationFormObject(that.validate.currentForm);

//把字符串格式转化为日期类
      let starttime = new Date(that.startTime );
      let endtime = new Date(that.endTime);
//进行比较
        if(endtime <= starttime){
          layer.msg('结束时间不能小于或等于开始时间!', {
            time: 3000, //3s后自动关闭
          });
          return;
        }
      dataObj.startTime = formatData(dataObj.startTime);
      dataObj.endTime = formatData(dataObj.endTime);
      console.log(dataObj )
      that.$post(
        that.urls.addBaseConstruction,
        dataObj
      )
        .then(function(res) {
          if(res.success) {
            that.Specialist = false;
            layer.msg('新增建设成功！', {
              time: 3000, //3s后自动关闭
            });
          }else {
            layer.msg('新增建设失败！', {
              time: 3000, //3s后自动关闭
            });
          }
        })
    },

    // 提交建设upd
    subBaseConstructionUpd: function () {
      let that = this;

      let flg = that.validate2.form();
      if(! flg){
        return;
      }

      let  dataObj = that.combinationFormObject(that.validate2.currentForm);

//把字符串格式转化为日期类
      let starttime = new Date(dataObj.startTime );
      let endtime = new Date(dataObj.endTime);
//进行比较
      if(starttime >= endtime){
        layer.msg('结束时间不能小于或等于开始时间!', {
          time: 3000, //3s后自动关闭
        });
        return;
      }
      dataObj.startTime = formatData(dataObj.startTime);
      dataObj.endTime = formatData(dataObj.endTime);
      dataObj.id = that.attId;

      that.$post(
        that.urls.editBaseConstruction,
        dataObj
      )
        .then(function(res) {
          if(res.success) {
            that.SpecialistUpd = false;
            that.AllTickets();
            layer.msg('修改建设成功！', {
              time: 3000, //3s后自动关闭
            });

          }else {
            layer.msg('修改建设失败！', {
              time: 3000, //3s后自动关闭
            });
          }
        })
    },

		//共建协议模态框
		demand: function(id) {
      this.baseId = id;
      console.log(id)
     this.AgreementObj = {};
     this.type = 3;
			this.demandModelShow = true;
		},
		//新增建设模态框
		SpecialistBtn: function(obj) {
      this.validate.resetForm();
      if(obj){
        this.obj = obj;
        this.startTime = obj.startTime;
        this.endTime = obj.endTime;
      }


      $('#baseId').val('');
      $('#constructionMatters').val('');

      $('#startTime').val('');
      $('#endTime').val('');
      this.FileUploadAtt = [];
      this.attachment ="" ;
			this.Specialist = true;
		},
		//基地建设
		AllTickets: function(id) {
       let that = this;
       if(id){
         that.page2 = 1;
         that.id = id;
       }
      that.$post(
        that.urls.getConstructionPage,
        {"baseId": that.id,"pageNum":that.page2, "pageSize": that.size2}
      )
        .then(function(res) {
          if(res.success) {
         that.construction = res.pageInfo.list;
            that.page2 = res.pageInfo.pageNum;
            that.total2 = res.pageInfo.total;
          }
        })

      that.Tickets = true;
		},
		//基地退出申请
		quitApplication: function(id, status, name) {
		  let that = this;
		  that.baseName = name;

		    if(status == 2){
        layer.alert("您已申请退出！");
		      return;
        }
		    that.baseId = id;
         console.log(id)
      console.log(that.baseId)

      that.quitFile = '';
      that.FileUpload = [];
      $('#quitReason').val('');

			this.QuitApplication = true;
		},
		//申请状态
		applicationStatus: function(id) {
		  let that = this;
      that.base = {};
      // 基地信息
      that.$post(
        that.urls.getBaseAreas, {
          "id": id,
        }
      )
        .then(function(res) {
          if(res.success) {
            that.base = res.data;
          }
        })

			this.ApplicationStatus = true;
		},
    // 基地终止
    temapplicationStatus: function(id) {
      let that = this;
      that.base = {};
      // 基地信息
      that.$post(
        that.urls.getBaseAreas, {
          "id": id,
        }
      )
        .then(function(res) {
          if(res.success) {
            that.base = res.data;
          }
        })
      this.temApplicationStatus = true;
    },

		//关闭模态框
		closeModel: function() {
			this.page2 = 1;
			this.SpecialistUpd = false;
			this.SpecialistView = false;
			this.temApplicationStatus = false;
			this.Application = false;
			this.Specialist = false;
			this.demandModelShow = false;
			this.Tickets = false;
			this.QuitApplication = false;
			this.ApplicationStatus = false;
		
		},
		/*关闭查看建设详情弹框*/
		closeSpecialistView:function(){
			this.SpecialistView = false;
		},
		/*关闭修改建设弹框*/
		closeModifyModel:function(){
		  this.AllTickets();
			this.SpecialistUpd = false;
		},
    // 跳转到预览
    toSrc: function (url) {
    //  console.log(url)
      if(url == null || url == undefined || url == ''){
        layer.msg('暂无附件', {
          time: 3000, //3s后自动关闭
        });
        return;
      }
      window.open(this.thatUrl + url);
    },
    //下载资源
    downloadResources: function(filePath) {
      if(filePath != null && filePath != "") {
        window.location.href = this.urls.download + "?path=" + filePath;
      }else {
        layer.msg('暂无附件', {
          time: 3000, //3s后自动关闭
        });
      }
    },

    // 提交退出申请
    subReason: function () {
      let that = this;
      if (that.baseId == undefined) {
        return;
      }
      let quitReason = $('#quitReason').val();
      let quitFile = $('#quitFile').val();

      if(quitReason == null || quitReason == ''){
      layer.msg('请输入退出原因', {
        time: 3000, //3s后自动关闭
      });
      return;
    }

        if(quitReason.length >100){
          layer.msg('内容最多只能输入100个字!', {
            time: 3000, //3s后自动关闭
          });
          return;
        }


      //let  dataObj = that.combinationFormObject(that.validate.currentForm);
     // 修改基地状态为推出
      that.$post(
        that.urls.editBaseAreas, {
          "id": that.baseId, "quitReason": quitReason, "status": 2, "quitFile": quitFile
        }
      )
        .then(function(res) {
          if(res.success) {
            layer.msg('成功提交基地退出申请！', {
              time: 3000, //3s后自动关闭
            });
            that.QuitApplication = false;
            that.getBase();
          }else {
            layer.msg('提交基地退出申请失败！', {
              time: 3000, //3s后自动关闭
            });
          }
        })


    },

    subStr: function (str) {
      if(str.length > 10){
        let s = str.substr(0, 8);
        return s+ '...';
      }else {
        return str;
      }
    },

    subStrName: function (str) {
        if(str){
          if(str.length > 18){
            let s = str.substr(0, 18);
            return s+ '...';
          }else {
            return str;
          }
        }
    },



    delAtt: function () {
      this.FileUploadAtt = [];
      this.attachment = '';
      this.obj.attachment = '';
      this.FileUpload = [];
      this.quitFile = '';
    },

    // 删除建设
    delConstruction: function (id) {
      console.log(id)
      let that = this;
      layer.confirm('你确定要删除吗?', {icon: 3, title:'提示'}, function(index){


        that.$post(
          that.urls.removeBaseConstruction,
          {"id": id}
        )
          .then(function(res) {
            if(res.success) {
              layer.msg('删除建设成功!', {
                time: 3000, //3s后自动关闭
              });
              that.AllTickets();
            }else {
              layer.msg('删除建设失败!', {
                time: 3000, //3s后自动关闭
              });
            }
          })
      });

    },

    // 建设查看
    viewConstruction: function (o) {
      o.startTime = formatData(o.startTime);
      o.endTime = formatData(o.endTime);

      this.obj = o;
      this.SpecialistView = true;
      /*this.Tickets = false;*/


    },

    //
    updConstruction: function (o) {
      let that = this;

      that.obj = o;
      $('#baseIdThe').val(that.obj.baseId);
      if(that.obj.id > 0){
        that.attId = o.id;
      }

      this.validate2.resetForm();
    //  o.startTime = formatData(o.startTime);
    //  o.endTime = formatData(o.endTime);

      this.SpecialistUpd = true;
      /*this.Tickets = false;*/

      let enclosureList = [];  // 查看
     /* enclosureList.push({
        "name": that.getFileName(that.getFileName(o.attachment)),
        "url":  o.attachment
      });*/
      
      if(that.getFileName(that.getFileName(o.attachment))){
      	enclosureList.push(that.getFileName(that.getFileName(o.attachment)));
      }
      that.FileUploadAtt = enclosureList;

    },

    // 共建协议
    subAgreement: function () {
      let that = this;
      console.log(that.type)
       console.log(that.baseId)
       if(!that.baseId){
         return;
       }

      that.AgreementObj.id = that.baseId;
      console.log(that.AgreementObj)

      that.$post(
        that.urls.editBaseAreas,
      {"id": that.baseId, "reserved2":   JSON.stringify(that.AgreementObj)}
      )
        .then(function(res) {
          if(res.success) {
            let msg = "";
            if(that.type == 1){
              msg = '修改共建协议成功!'
            }else {
              msg = '保存共建协议成功!'
            }
            layer.msg(msg, {
              time: 3000, //3s后自动关闭
            });
            that.demandModelShow = false;
            that.getBase();
          }else {
            let msg = "";
            if(that.type == 1){
              msg = '修改共建协议失败!'
            }else {
              msg = '保存共建协议失败!'
            }
            layer.msg(msg, {
              time: 3000, //3s后自动关闭
            });
          }
        })

    },
    // 查看共建协议
    demandView: function (obj,id) {
      let that = this;
      that.type = 0;
      let o = JSON.parse(obj.value);

      that.demandModelShow = true;
      that.AgreementObj = o;
      that.baseId = id;
    },
    // 修改共建协议
    demandUpd: function (obj, id) {
      let that = this;
      that.type = 1;
      let o = JSON.parse(obj.value);

      that.demandModelShow = true;
      that.AgreementObj = o;
      that.baseId = id;
    }


	}
}
